In C, an enum (short for enumeration) is a user-defined data type that consists of a set of named constants, known as enumerators. Each enumerator represents an integer value, and by default, the first enumerator has a value of 0, and subsequent enumerators have values incremented by 1 from the previous one.
To define an enum, use the enum keyword followedby the name of the enum and a list of enumerator names enclosed in curly braces.
enum enum_name {
enumerator1,
enumerator2,
...
};
By default, enum elements start from 0, but can explicitly assign values to enumerators.
#include <stdio.h>
// Defining an enum for days of the week
enum Days {
SUNDAY, // 0
MONDAY, // 1
TUESDAY, // 2
WEDNESDAY, // 3
THURSDAY, // 4
FRIDAY, // 5
SATURDAY // 6
};
int main() {
enum Days today = WEDNESDAY;
switch (today) {
case SUNDAY:
printf("Today is Sunday.\n");
break;
case MONDAY:
printf("Today is Monday.\n");
break;
case TUESDAY:
printf("Today is Tuesday.\n");
break;
case WEDNESDAY:
printf("Today is Wednesday.\n"); // This case is executed
break;
case THURSDAY:
printf("Today is Thursday.\n");
break;
case FRIDAY:
printf("Today is Friday.\n");
break;
case SATURDAY:
printf("Today is Saturday.\n");
break;
default:
printf("Invalid day.\n");
}
return 0;
}
Today is Wednesday.
What is an enum in C?
What is the purpose of an enum in C?
How are enum constants defined in C?
What is the default type of an enum in C?
How can you access enum constants in C?